from django.db.models import Max
from django.conf import settings
from rest_framework import serializers

from utils.func import is_correct

from datetime import datetime
from decimal import Decimal, getcontext


def create_dikang_mingan(instance):
    """仅供prj002使用
    自动生成[胰岛素抵抗指数（HOMA-IR）, 胰岛素敏感指数（ISI）]
    """
    xt = instance.check_xuetang
    yds = instance.check_yidaosu

    # Fix: 解决生成指数的运算类型不符, 出现decimal无法除以float问题
    getcontext().prec = 5

    if all([xt, yds]):
        num = xt * yds
        instance.yidaosu_dikang = '%.2f' % (num / Decimal(22.5))
        instance.yidaosu_mingan = '%.2f' % (Decimal(1) / num)

    instance.save()
    return instance


def create_bmi_and_whr(instance):
    """仅供prj002使用
    自动生成[体重指数(BMI), 腰臀比(WHR)]
    """
    height = instance.height
    weight = instance.weight
    hipline = instance.hipline
    waistline = instance.waistline

    if all([height, weight]):
        instance.bmi = '%.2f' % (weight / height)

    if all([hipline, waistline]):
        instance.whr = '%.2f' % (waistline / hipline)

    return instance


# def create_degree_of_completion(instance, necessary_info, necessary_cure):
#     """
#     自动生成信息完成度
#     : return -- dict()
#     """
#     len_info_necessary = len(necessary_info)
#     len_cure_necessary = len(necessary_cure)
#     current_info = []
#     current_cure = []

#     # info
#     for i in necessary_info:
#         if getattr(instance, i):
#             current_info.append(i)

#     len_info_now = len(current_info)

#     degree_info = (len_info_now / len_info_necessary) * 50

#     # cure
#     try:
#         instance_cure = instance.cure
#     except Exception:
#         pass
#     else:
#         for cure_key in necessary_cure:
#             inner_list = []
#             for ck in cure_key:
#                 if getattr(instance_cure, ck):
#                     inner_list.append(ck)

#             if not inner_list:
#                 continue

#             current_cure.append(inner_list)

#     degree_cure = (len(current_cure) / len_cure_necessary) * 50

#     degree = degree_info + degree_cure

#     # instance.degree_of_completion = degree_info
#     # data = {
#     #     'degree_of_completion': '%.2f' % degree
#     # }
#     return '%.2f' % degree


def create_today_number():
    today = datetime.today()
    current_year = today.year
    current_month = today.month
    current_day = today.day
    serial = '%s%02d%02d%04d' % (current_year, current_month, current_day, 1)
    return serial


def generate_current_day():
    today = datetime.today()
    current_year = today.year
    current_month = today.month
    current_day = today.day
    current = '%s%02d%02d' % (current_year, current_month, current_day)
    return current


def create_questionnare_number(model_name):
    # 创建问卷编码
    s_current_date = generate_current_day()
    # 查询当天的问卷编码最大值
    max_questionnaire_id = model_name.objects.filter(serial__startswith=s_current_date).aggregate(Max('serial'))

    max_id = max_questionnaire_id.get('serial__max', None)

    if max_id:
        if is_correct(max_id):
            now_number = int(max_id[-4:]) + 1
            if now_number > settings.PRJ003_MAX_SERIAL:
                raise ValueError('问卷编码已经入库超过最大值')

            serial = '{}'.format(int(max_id) + 1)
        else:
            raise ValueError('问卷编码格式不正确')
    else:
        serial = create_today_number()

    return serial


def create_instance(validate_data, model_name):
    if validate_data.get('serial'):
        validate_data.pop('serial')

    try:
        serial = create_questionnare_number(model_name)
        serial_date = is_correct(serial)
    except Exception as error:
        raise serializers.ValidationError(error)

    if not serial_date:
        raise serializers.ValidationError('问卷编码格式不正确')

    validate_data.update({'serial': serial})

    return validate_data
